import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/map_editor_provider.dart';
import '../models/map_models.dart';
import 'image_import_dialog.dart';
import 'rect_image.dart';

class TilePalette extends StatelessWidget {
  const TilePalette({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<MapEditorProvider>(
      builder: (context, provider, child) {
        return Container(
          height: 160,
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey[300]!),
          ),
          child: Column(
            children: [
              // 顶部工具栏，类似原Android的按钮栏
              Container(
                height: 50,
                padding: const EdgeInsets.symmetric(horizontal: 8),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  border: Border(
                    bottom: BorderSide(color: Colors.grey[300]!),
                  ),
                ),
                child: Row(
                  children: [
                    // 当前选中的图块预览，对应原代码的selectImage
                    Container(
                      width: 40,
                      height: 40,
                      margin: const EdgeInsets.only(right: 8),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: _buildSelectedTilePreview(provider),
                    ),
                    const Text(
                      '图块选择',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                    const Spacer(),
                    // 添加图块按钮
                    IconButton(
                      onPressed: () => _showAddImageDialog(context),
                      icon: const Icon(Icons.add_photo_alternate),
                      tooltip: '添加图片',
                      iconSize: 20,
                    ),
                  ],
                ),
              ),
              // 图块网格，对应原Android的GridView
              Expanded(
                child: _buildTileGrid(provider),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildSelectedTilePreview(MapEditorProvider provider) {
    final selectedTileId = provider.selectedTileId;
    
    if (selectedTileId == 0 || !provider.hasMap) {
      return const Icon(
        Icons.clear,
        color: Colors.grey,
        size: 20,
      );
    }

    // 查找对应的图块集和索引
    for (final tileSet in provider.currentMap!.tileSets) {
      if (selectedTileId >= tileSet.firstGid && 
          selectedTileId < tileSet.firstGid + tileSet.tileCount) {
        final tileIndex = selectedTileId - tileSet.firstGid;
        
        // 计算图块在图片中的位置
        final row = tileIndex ~/ tileSet.columns;
        final col = tileIndex % tileSet.columns;
        final sourceX = col * tileSet.tileWidth.toDouble();
        final sourceY = row * tileSet.tileHeight.toDouble();
        
        return ClipRRect(
          borderRadius: BorderRadius.circular(2),
          child: RectImage.fromImage(
            imagePath: tileSet.imagePath,
            sourceX: sourceX,
            sourceY: sourceY,
            sourceWidth: tileSet.tileWidth.toDouble(),
            sourceHeight: tileSet.tileHeight.toDouble(),
            fit: BoxFit.cover,
            errorWidget: Container(
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(2),
              ),
              child: Center(
                child: Text(
                  '$tileIndex',
                  style: const TextStyle(
                    fontSize: 10,
                    color: Colors.black54,
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }

    // 如果没找到对应的图块集，显示ID
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(2),
      ),
      child: Center(
        child: Text(
          selectedTileId.toString(),
          style: const TextStyle(
            fontSize: 10,
            color: Colors.black54,
          ),
        ),
      ),
    );
  }

  Widget _buildTileGrid(MapEditorProvider provider) {
    // 只显示自定义图块集的图块，移除基础颜色图块
    List<Map<String, dynamic>> allTiles = [];
    
    if (provider.hasMap) {
      for (final tileSet in provider.currentMap!.tileSets) {
        for (int i = 0; i < tileSet.tileCount; i++) {
          allTiles.add({
            'id': tileSet.firstGid + i,
            'name': '${tileSet.name}_$i',
            'tileSet': tileSet,
            'tileIndex': i,
            'imagePath': tileSet.imagePath,
            'tileWidth': tileSet.tileWidth,
            'tileHeight': tileSet.tileHeight,
            'columns': tileSet.columns,
            'isCustom': true,
          });
        }
      }
    }

    if (allTiles.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.image_outlined,
              size: 48,
              color: Colors.grey,
            ),
            SizedBox(height: 8),
            Text(
              '暂无图块',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            ),
            SizedBox(height: 4),
            Text(
              '点击上方按钮添加图片',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 12,
              ),
            ),
          ],
        ),
      );
    }

    return GridView.builder(
      padding: const EdgeInsets.all(4),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 8,  // 对应原Android的numColumns="8"
        crossAxisSpacing: 4, // 对应原Android的horizontalSpacing="5dp"
        mainAxisSpacing: 4,
        childAspectRatio: 1,
      ),
      itemCount: allTiles.length,
      itemBuilder: (context, index) {
        final tile = allTiles[index];
        final tileId = tile['id'] as int;
        final isSelected = provider.selectedTileId == tileId;

        return GestureDetector(
          onTap: () {
            provider.selectTile(tileId);
            // 选择图块后自动切换到编辑模式，参考Android版本的行为
            if (provider.editMode != EditMode.edit) {
              provider.setEditMode(EditMode.edit);
            }
          },
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                color: isSelected ? Colors.blue : Colors.grey[400]!,
                width: isSelected ? 2 : 1,
              ),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Container(
              margin: const EdgeInsets.all(1),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2),
              ),
              child: _buildTileImage(tile),
            ),
          ),
        );
      },
    );
  }

  Widget _buildTileImage(Map<String, dynamic> tile) {
    final imagePath = tile['imagePath'] as String?;
    final tileIndex = tile['tileIndex'] as int;
    final tileWidth = tile['tileWidth'] as int;
    final tileHeight = tile['tileHeight'] as int;
    final columns = tile['columns'] as int;
    
    if (imagePath == null || !File(imagePath).existsSync()) {
      // 如果图片不存在，显示索引数字
      return Container(
        color: Colors.grey[200],
        child: Center(
          child: Text(
            '$tileIndex',
            style: const TextStyle(
              fontSize: 12,
              color: Colors.black54,
            ),
          ),
        ),
      );
    }

    // 计算图块在图片中的位置
    final row = tileIndex ~/ columns;
    final col = tileIndex % columns;
    final sourceX = col * tileWidth.toDouble();
    final sourceY = row * tileHeight.toDouble();

    // 使用RectImage.fromImage控件显示图块
    return RectImage.fromImage(
      imagePath: imagePath,
      sourceX: sourceX,
      sourceY: sourceY,
      sourceWidth: tileWidth.toDouble(),
      sourceHeight: tileHeight.toDouble(),
      fit: BoxFit.cover,
      errorWidget: Container(
        color: Colors.grey[200],
        child: Center(
          child: Text(
            '$tileIndex',
            style: const TextStyle(
              fontSize: 12,
              color: Colors.black54,
            ),
          ),
        ),
      ),
    );
  }

  void _showAddImageDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const ImageImportDialog(),
    );
  }
}